package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.BaseColorInfo;
import com.yld.car.domain.EditCarInfo;

public class ExteriorActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.base_list);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		this.settingTitle(R.id.title, "选择外观颜色");

		list = (ListView) findViewById(R.id.list1);
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		Intent intent = this.getIntent();

		cId = intent.getStringExtra("cId");
		isEditor = intent.getBooleanExtra("isEditor", false);
		System.out.println("cId=====" + cId);
		utils = NetworkProgressUtils.getInstance();
		new MyExteriorTask().execute(cId);
	}

	private boolean isEditor;
	private ProgressBar mProgressBar;
	private NetworkProgressUtils utils;

	private ListView list;
	private String cId;

	private class MyExteriorTask extends
			AsyncTask<String, String, ArrayList<BaseColorInfo>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mProgressBar.setVisibility(View.VISIBLE);
			list.setVisibility(View.GONE);
		}

		@Override
		protected ArrayList<BaseColorInfo> doInBackground(String... params) {

			HashMap<String, String> allParams = new HashMap<String, String>();
			allParams.put("seriesId", params[0]);

			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(19),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(19),
					ConstantUtils.GET_OUTER_EXTERIOR_BY_SERIES_ID_URL,
					allParams);
			// System.out.println(o);
			ArrayList<BaseColorInfo> all = utils.parseJsonColor(o.toString(),
					"table", true);

			return all;
		}

		@Override
		protected void onPostExecute(ArrayList<BaseColorInfo> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			mProgressBar.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
			if (result != null) {

				List<SimpeCircleItem> allSimpeCircleItems = new ArrayList<ExteriorActivity.SimpeCircleItem>();
				List<Map<String, String>> allItems = new ArrayList<Map<String, String>>();
				for (BaseColorInfo baseColorInfo : result) {

					HashMap<String, String> hm = new HashMap<String, String>();
					hm.put("id", baseColorInfo.getId());
					hm.put("name", baseColorInfo.getDdname());
					hm.put("show", "0");
					//添加颜色的简称
					hm.put("shortname", baseColorInfo.getDdshortname());
					allItems.add(hm);

				}
				SimpeCircleItem simpeCircleItem = new SimpeCircleItem("",
						allItems);

				allSimpeCircleItems.add(simpeCircleItem);

//				List<Map<String, String>> allCustomItems = new ArrayList<Map<String, String>>();
//
//				HashMap<String, String> hm = new HashMap<String, String>();
//				hm.put("id", "custom");
//				hm.put("name", "添加自定义颜色");
//				hm.put("show", "1");
//				allCustomItems.add(hm);
//				allSimpeCircleItems
//						.add(new SimpeCircleItem("", allCustomItems));

				SimpleListCircleAdapter adapter = new SimpleListCircleAdapter(
						ExteriorActivity.this, allSimpeCircleItems);
				list.setAdapter(adapter);

			}
		}
	}

	private class SimpleListCircleAdapter extends BaseAdapter implements
			OnItemClickListener {

		private Context context;
		private List<SimpeCircleItem> listData;
		private LayoutInflater mInflater;

		public SimpleListCircleAdapter(Context context,
				List<SimpeCircleItem> listData) {

			this.context = context;
			this.listData = listData;
			mInflater = LayoutInflater.from(this.context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View localView = this.mInflater.inflate(
					R.layout.base_list_items_circle_list, null);
			SimpeCircleItem localSimpeCircleItem = (SimpeCircleItem) this.listData
					.get(position);
			TextView localTextView = (TextView) localView
					.findViewById(R.id.itemTitle);
			localTextView.setText(localSimpeCircleItem.getTitle());
			if (localSimpeCircleItem.getTitle().equals(""))
				localTextView.setVisibility(View.GONE);
			SimpleList2Adapter localSimpleList2Adapter = new SimpleList2Adapter(
					this.context, localSimpeCircleItem.getListData());
			ListView localListView = (ListView) localView
					.findViewById(R.id.itemList);
			localListView.setAdapter(localSimpleList2Adapter);
			localListView.setOnItemClickListener(this);
			return localView;
		}

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			// System.out.println("onItemClick==="+adapterView.getAdapter().getItem(position));
			HashMap<String, String> hm = (HashMap<String, String>) adapterView
					.getAdapter().getItem(position);
			String show = hm.get("show");
			String name = hm.get("name");
			//String shortname=hm.get("shortname");
			
			if ("0".equals(show)) {

				if (isEditor) {
					EditCarInfo e = mApp.getmEditCarInfo();
					e.setWsid(hm.get("id"));
					e.setWsname(name);
					
					mApp.setmEditCarInfo(e);
				} //else {
					mApp.setmEnteriorColor(hm);
				//}

				finish();
			} else if ("1".equals(show)) {

				String prompt = "请添加外观颜色";

				View v = LayoutInflater.from(getBaseContext()).inflate(
						R.layout.custom_color, null);

				final EditText nameText = (EditText) v.findViewById(R.id.name);
				final EditText shortNameText = (EditText) v
						.findViewById(R.id.shortName);
				addCustomColor(v, prompt,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								/*
								 * 自定义某一系列下的外饰、内饰/皮饰、木饰、排量 发布车源时使用
								 * AddOuterExteriorBySeriesId(string seriesId,
								 * string name, string shortName, string oper)
								 * 参数一：系列ID 参数二：要添加的名称
								 * 参数三：要添加的名称简称（此标示只用于添加外饰和内饰时使用） 参数四：区别标示,
								 * ws:外饰 ns:内饰/皮饰 ms:木饰 lg：轮毂 pl：排量
								 */
								final String customColorName = nameText
										.getText().toString();
								final String cusotmColorShortName = shortNameText
										.getText().toString();
								new Thread(new Runnable() {

									@Override
									public void run() {

										// 添加之前要判断是否有存在的外饰
										/*
										 * ExistThingsBySeriesId(string
										 * seriesId, string name, string oper)
										 * 参数一：系列ID 参数二：要添加的名称 参数三：区别标示, ws:外饰
										 * ns:内饰/皮饰 ms:木饰 lg：轮毂 pl：排量
										 */
										HashMap<String, String> allParams = new HashMap<String, String>();

										allParams.put("seriesId", cId);
										allParams.put("name", customColorName);
										allParams.put("oper", "ws");
										Object o = utils
												.getWebservicesByData(
														ConstantUtils.NAME_SPACE,
														ConstantUtils.ALL_METHROD_NAME
																.get(13),
														ConstantUtils.NAME_SPACE
																+ ConstantUtils.ALL_METHROD_NAME
																		.get(13),
														ConstantUtils.GET_EXIST_THINGS_BY_SERIES_ID_URL,
														allParams);
										String result = "";
										if (o.toString().indexOf("0") >= 0) {
											// result = "可以添加";

											allParams = new HashMap<String, String>();
											allParams.put("seriesId", cId);
											allParams.put("name",
													customColorName);
											allParams.put("shortName",
													cusotmColorShortName);
											allParams.put("oper", "ws");
											o = utils
													.getWebservicesByData(
															ConstantUtils.NAME_SPACE,
															ConstantUtils.ALL_METHROD_NAME
																	.get(11),
															ConstantUtils.NAME_SPACE
																	+ ConstantUtils.ALL_METHROD_NAME
																			.get(11),
															ConstantUtils.GET_ADD_OUTER_EXTERIOR_BY_SERIES_ID_URL,
															allParams);

											// result = "";

											if (o.toString().indexOf("1") >= 0) {
												result = "添加成功";
												finish();
											} else {
												result = "添加失败,请稍候重试";
											}

											Message msg = handler
													.obtainMessage();
											msg.obj = result;
											handler.sendMessage(msg);
										} else {
											result = "添加的名称已存在，请确认";
											Message msg = handler
													.obtainMessage();
											msg.obj = result;
											handler.sendMessage(msg);
											// finish();

										}

										// System.out.println(o);

									}
								}).start();

								HashMap<String, String> hm = new HashMap<String, String>();
								hm.put("id", "custom");
								hm.put("name", customColorName);
								hm.put("show", "1");
								mApp.setmEnteriorColor(hm);

							}

						}, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						});
			}
		}
	}

	private class SimpeCircleItem {
		private List<Map<String, String>> listData;
		private String title;

		public SimpeCircleItem(String paramString,
				List<Map<String, String>> paramList) {
			setTitle(paramString);
			setListData(paramList);
		}

		public List<Map<String, String>> getListData() {
			return this.listData;
		}

		public String getTitle() {
			return this.title;
		}

		public void setListData(List<Map<String, String>> paramList) {
			this.listData = paramList;
		}

		public void setTitle(String paramString) {
			this.title = paramString;
		}
	}

	public class SimpleList2Adapter extends BaseAdapter {
		private List<Map<String, String>> listData;
		private LayoutInflater mInflater;

		public SimpleList2Adapter(Context paramContext,
				List<Map<String, String>> paramList) {
			this.mInflater = LayoutInflater.from(paramContext);
			this.listData = paramList;
		}

		public int getCount() {
			return this.listData.size();
		}

		public Object getItem(int paramInt) {
			return this.listData.get(paramInt);
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		public View getView(int paramInt, View paramView,
				ViewGroup paramViewGroup) {
			View localView = this.mInflater.inflate(
					R.layout.base_list_items_simple, null);
			localView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			Map<String, String> localMap = (Map<String, String>) this.listData
					.get(paramInt);
			localView.setTag(localMap);
			((TextView) localView.findViewById(R.id.itemContent))
					.setText((CharSequence) localMap.get("name"));
			ImageView localImageView = (ImageView) localView
					.findViewById(R.id.nextStep);
			if (localMap.get("show").equals("1")) {
				localImageView.setVisibility(View.VISIBLE);
				return localView;
			}
			localImageView.setVisibility(View.GONE);
			return localView;
		}

		public boolean isEnabled(int paramInt) {
			return super.isEnabled(paramInt);
		}
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method
			// stub
			super.handleMessage(msg);

			Toast.makeText(getApplicationContext(), msg.obj.toString(),
					Toast.LENGTH_SHORT).show();

		}
	};
}
